package com.stanley.alogrithm.tree;

import com.stanley.alogrithm.TreeNode;

public class TreeTravsersal {
    public static void main(String[] args) {
        //int val = Math.pow(10, 3);
        TreeTravsersal tt = new TreeTravsersal();
        TreeNode root = tt.buildTree();
        int result = tt.sumNumbers(root);
        System.out.print("result: " + result);
    }

    private TreeNode buildTree() {
        TreeNode root = new TreeNode();
        root.val = 1;
        TreeNode left = new TreeNode();
        left.val = 0;
        TreeNode right = new TreeNode();
        right.val = 3;
        root.left = left;
        //root.right = right;
        return root;
    }

    private int totalSum = 0;
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        // write code here
        if (root == null) {
            return 0;
        }
        recursiveSumPath(root, 0);
        return totalSum;
    }

    private void loopSumPath(TreeNode node) {
        int result = 0;
        TreeNode current = node;
        int previousPathSum = 0;
        int level = 0;
        while (true) {
            if(level == 0 && current == null) {
                return;
            }
            if (current.left == null && current.right == null) {
                result += previousPathSum + current.val;
            }
            if (current.left != null) {
                level++;
                current = current.left;
            }

        }
    }

    private void recursiveSumPath(TreeNode node, int parentSum) {
        //currentSum*10 + dfsOnePath(node.left, )
        int currentLevelSum = parentSum*10 + node.val;
        if (node.left!=null) {
            recursiveSumPath(node.left, currentLevelSum);
        }
        if (node.right!=null) {
            recursiveSumPath(node.right, currentLevelSum);
        }

        if(node.left == null && node.right == null) {
            totalSum += currentLevelSum;
        }
    }
}
